package fm.dongman.modellib.local;

import android.content.Context;

import org.jetbrains.annotations.NotNull;

import fm.dongman.animefm.contractlib.contract.HomeContract;
import fm.dongman.animefm.contractlib.model.HomeDataModel;

/**
 * 主页本地数据源
 * Created by shize on 2017/10/10.
 */

public class HomeLocalDataSource implements HomeContract.IHomeDataSource {
    private static HomeLocalDataSource INSTANCE; // 持有实例

    private DataOperationHelper dataOperationHelper;

    private HomeLocalDataSource(Context context){
        dataOperationHelper = DataOperationHelper.getDataOperationHelper(context);
    }

    /**
     * @return 获取本地数据源实例
     */
    public static HomeLocalDataSource getInstance(Context context) {
        if (INSTANCE == null) {
            INSTANCE = new HomeLocalDataSource(context);
        }
        return INSTANCE;
    }

    @Override
    public void getData(@NotNull LoadSourceCallback<? super HomeDataModel> callback) {
        HomeDataModel homeDataModel = new HomeDataModel();
        homeDataModel.setNewArticles(dataOperationHelper.downArticleData());
        homeDataModel.setBanners(dataOperationHelper.downBannerData());
        homeDataModel.setFMRecommends(dataOperationHelper.downComicData());
        homeDataModel.setNewComments(dataOperationHelper.downCommentData());
        homeDataModel.setSheets(dataOperationHelper.downSheetData());
        homeDataModel.setRankComic(dataOperationHelper.downRankComicData());
        if (dataOperationHelper.downArticleData().size() != 0 ) {
            callback.onDataLoaded(homeDataModel);
        }
        else {
            callback.onDataLoadFiled();
        }
    }

    @Override
    public void saveData(HomeDataModel dataModel) {
        dataOperationHelper.addArticleData(dataModel.getNewArticles());
        dataOperationHelper.addBanner(dataModel.getBanners());
        dataOperationHelper.addComic(dataModel.getFMRecommends());
        dataOperationHelper.addComment(dataModel.getNewComments());
        dataOperationHelper.addSheet(dataModel.getSheets());
        dataOperationHelper.addRankComic(dataModel.getRankComic());
    }

    @Override
    public void refreshData() {
        // 不需要做操作，因为刷新数据操作是在 HomeRepository 里进行操作的
    }

    @Override
    public void offLine() {
        // 不需要做操作
    }
}
